package com.ym.manager.admin.notice;

import com.ym.utils.ResultUtil;
import com.ym.utils.StringHandler;
import okhttp3.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: dhf
 * @ClassName: NoticeController
 * @Date: 2022/9/23 11:01
 * @Description:
 * @Version: 1.0
 */

@Controller
@RequestMapping("/user/notice/")
public class NoticeController {
    @RequestMapping("/index")
    public String index(){
        return "/sys/notice/addNotice";
    }

    @RequestMapping("/addNotice")
    @ResponseBody
    public String addNotice(String title,String content,int isTest,int isAll){
        Map<String,Object> map = ResultUtil.result();
        if(isTest==1){
            return ResultUtil.toJSON(map);
        }
        if(StringHandler.isEmpty(title)){
            map.put("code",500);
            map.put("msg","标题不能为空");
            return ResultUtil.toJSON(map);
        }
        if(StringHandler.isEmpty(content)){
            map.put("code",500);
            map.put("msg","内容不能为空");
            return ResultUtil.toJSON(map);
        }
        OkHttpClient client = new OkHttpClient();
        Map<String,Object> param = new HashMap<>();
        param.put("title",title);
        param.put("content",content);
        if(isAll==0){
            param.put("isAll",true);
        }
        if(isAll==1){
            param.put("isAll",false);
        }
        String url = "http://172.24.194.56:8082/sys/notice/background/addNotice";
        if(isAll==2){
            url = "http://172.24.194.56:8082/sys/notice/background/user/addNotice";
        }
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON, com.alibaba.fastjson.JSON.toJSONString(param)))
                .addHeader("Content-Type","'application/json'")
                .build();
        try{
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new IOException("post Unexpected code " + response);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
